package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.dto.UpdateArticleMessage;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.Threadlocals.UserThreadLocalUtil;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-13
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {

    @Autowired
    private IApBehaviorEntryService entryService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Value("${topic.hotArticleScoreTopic}")
    private String hotArticleScoreTopic;


    @Override
    public ResponseResult saveLikes(LikesBehaviorDto dto) {
        // 获取当前登录的用户
        User user = UserThreadLocalUtil.get();
        // 获取行为实体
        ApBehaviorEntry entry = entryService.getEntry(dto.getUserId(), dto.getEquipmentId());

        // 构建点赞行为记录
        ApLikesBehavior behavior = new ApLikesBehavior();
        behavior.setEntryId(entry.getId());
        behavior.setArticleId(dto.getArticleId());
        behavior.setType(0);
        behavior.setOperation(dto.getOperation());
        behavior.setCreatedTime(new Date());
        // 判断当前用户对这篇文章是否已经有点赞记录
        LambdaQueryWrapper<ApLikesBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApLikesBehavior::getArticleId, dto.getArticleId());
        query.eq(ApLikesBehavior::getEntryId, entry.getId());
        ApLikesBehavior one = this.getOne(query);
        if (one == null) {
            this.save(behavior);
            sendArticleBahaviorMsg(dto);
        } else {
            if (!one.getOperation().equals(dto.getOperation())) {
                one.setOperation(dto.getOperation());
                this.updateById(one);
                sendArticleBahaviorMsg(dto);
            }
        }
        return ResponseResult.okResult();
    }

    /**
     * 发送行为消息
     * @param dto
     */
    private void sendArticleBahaviorMsg(LikesBehaviorDto dto) {
        //TODO 发送操作行为到“计算热点文章分之话题中”
        //1.构建发送点赞行为消息对象 封装：文章ID，操作类型（阅读，点赞，评价，收藏） ，增量值
        UpdateArticleMessage message = new UpdateArticleMessage();
        message.setArticleId(dto.getArticleId());
        message.setType(1);
        message.setAdd(dto.getOperation() == 0 ? 1 : -1);
        //2.将消息发送到指定源话题中
        String val = JSON.toJSONString(message);
        kafkaTemplate.send(hotArticleScoreTopic, val);
    }
}
